package com.hqyj.util;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @author cz
 * 2021/8/12 9:32
 */
public class JdbcUtil {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        //读取properties文件
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");
        try {
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取Connection对象
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    //关闭Connection
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    //关闭ResultSet
    public static void closeResultSet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //关闭PreparedStatement
    public static void closePreparedStament(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //事务回滚
    public static void rollBack(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //关闭资源
    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs) {
        closeConnection(conn);
        closePreparedStament(ps);
        closeResultSet(rs);

    }
}

